package com.robot.orders.service;

import com.github.wxpay.sdk.WeChatPay;
import com.github.wxpay.sdk.WeChatPayUtil;
import com.robot.orders.config.WeChatPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wuyunbin
 */
@Service
public class WeChatPayService {

    private final WeChatPayConfig config = new WeChatPayConfig();

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public WeChatPayService() throws Exception {
    }

    public Map<String, String> pay(String openId, String ordersId, String amount) throws Exception {
        WeChatPay weChatPay;
        Map<String, String> result = new HashMap<String, String>();

        try {
            weChatPay = new WeChatPay(config);
            Map<String, String> data = new HashMap<>();

            data.put("appid", config.getAppId());
            data.put("mch_id", config.getMchId());
            data.put("nonce_str", String.valueOf(System.currentTimeMillis()));
            data.put("body", "付款");
            data.put("out_trade_no", ordersId);
            data.put("total_fee", amount);
            data.put("spbill_create_ip", "127.0.0.1");
            data.put("notify_url", config.getRedirectUri());
            if (openId != null) {
                data.put("openid", openId);
                data.put("trade_type", "JSAPI");
            } else {
                data.put("trade_type", "APP");

            }

            logger.info(data.toString());
            Map<String, String> response = weChatPay.unifiedOrder(data);
            logger.info(response.toString());

            if ("SUCCESS".equals(response.get("result_code"))) {
                result.put("appId", config.getAppId());
                LocalDateTime now = LocalDateTime.now();
                result.put("timeStamp", now.toEpochSecond(ZoneOffset.of("+8")) + "");
                result.put("signType", "MD5");
                result.put("prepay_id", response.get("prepay_id"));
                result.put("paySign", WeChatPayUtil.generateSignature(result, config.getKey()));

            }

        } catch (Exception e) {
            logger.info(e.getStackTrace().toString());
            logger.info(e.getMessage());
        }
        return result;
    }


    public Map<String, String> h5Pay(String ordersId, String amount, String ip) {

        WeChatPay weChatPay;
        Map<String, String> result = new HashMap<String, String>();

        try {
            weChatPay = new WeChatPay(config);
            Map<String, String> data = new HashMap<>();

            data.put("appid", config.getAppId());
            data.put("mch_id", config.getMchId());
            data.put("nonce_str", String.valueOf(System.currentTimeMillis()));
            data.put("body", "付款");
            data.put("out_trade_no", ordersId);
            data.put("total_fee", amount);
            data.put("spbill_create_ip", ip);
            data.put("notify_url", config.getRedirectUri());
            data.put("trade_type", "MWEB");
            data.put("scene_info", "{\"h5_info\": {\"type\":\"h5\"}");

            logger.info(data.toString());
            Map<String, String> response = weChatPay.unifiedOrder(data);
            logger.info(response.toString());

            if ("SUCCESS".equals(response.get("result_code"))) {
                result.put("appId", config.getAppId());
                LocalDateTime now = LocalDateTime.now();
                result.put("timeStamp", now.toEpochSecond(ZoneOffset.of("+8")) + "");
                result.put("signType", "MD5");
                result.put("prepay_id", response.get("prepay_id"));
                result.put("paySign", WeChatPayUtil.generateSignature(result, config.getKey()));

            }

        } catch (Exception e) {
            logger.info(e.getStackTrace().toString());
            logger.info(e.getMessage());
        }
        return result;
    }


    /**
     * 查询订单
     *
     * @param ordersId
     * @return
     */
    public Map<String, String> query(String ordersId) {
        WeChatPay weChatPay = null;

        try {
            weChatPay = new WeChatPay(config);
            Map<String, String> data = new HashMap<>();

            data.put("appid", config.getAppId());
            data.put("mch_id", config.getMchId());
            data.put("nonce_str", String.valueOf(System.currentTimeMillis()));
            data.put("out_trade_no", ordersId);

            Map<String, String> response = weChatPay.orderQuery(data);
            return response;
        } catch (Exception e) {
            logger.info(e.getStackTrace().toString());
        }

        return null;
    }


    public Map<String, String> getOpenId(String code) {
        Map<String, String> result = new HashMap<>();

        return result;
    }
}
